//
//  MainTabBarController.m
//  AmountBody
//
//  Created by chenzhihui on 14-12-8.
//  Copyright (c) 2017年 RCMTM. All rights reserved.
//

#import "MainTabBarController.h"
#import "AppDelegate.h"
#import "MainNavigationController.h"
#import "LoginViewController.h"
#import "LBTabBar.h"

#import "HomeViewController.h"
#import "PlaceOrderViewController.h"
#import "CutViewController.h"
#import "ShoppingCarViewController.h"
#import "NSObject+Extension.h"
#import "CustomViewController.h"
#import <AmountBody-Swift.h>

#define OneViewBG_TAG 111110
#define ImageView_TAG 111111
#define NoticeImageView_TAG 20000
#define TextView_TAG 111120
#define NeedToUpdateVersion_TAG 30000
#define custom_flag @"custom_list"//自定义文章flag


//判断系统版本大于10.0
#define IOS_VERSION_10 (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_9_x_Max)?(YES):(NO)

//#define BottomImageArray @[@"index_tabbar_home",@"index_t÷bbar_re",@"index_tabbar_caiji", @"index_tabbar_effect", @"index_tabbar_my"]


@interface MainTabBarController ()<LBTabBarDelegate>
@property (strong, nonatomic) UIImageView * noticeImage;

@property (strong, nonatomic) NSString *categoryUpdateTime;
@property (strong, nonatomic) UIView * backView;
@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) NSMutableDictionary * dataDic;

@end

@implementation MainTabBarController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"maintabbar");
    //检测更新
    [GYPNetworking checkversion:^(BOOL hasnewversion) {
        if (hasnewversion) {
            [UserManager hasNewVersion:@"1"];
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"发现新版本" message:@"发现新版本，是否前往更新？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction * defaultAction = [UIAlertAction actionWithTitle:@"去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //更新
                NSString * urlstr = DOWNLOADURL;
                urlstr = [urlstr stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
                NSURL *url = [NSURL URLWithString:urlstr];
                if (IOS_VERSION_10) {
                    [[UIApplication sharedApplication]openURL:url options:@{UIApplicationOpenURLOptionsSourceApplicationKey : @YES} completionHandler:^(BOOL success) {
                        
                        //成功后的回调
                        
                        if (!success) {
                            
                            //失败后的回调
                            
                        }
                        
                    }];
                }else{
                    [[UIApplication sharedApplication] openURL:url];
                    
                }
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:defaultAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }else{
            [UserManager hasNewVersion:@"0"];
        }
    }];

    _dataDic = [NSMutableDictionary dictionary];
    [self setUpAllChildVc];
    //创建自己的tabbar，然后用kvc将自己的tabbar和系统的tabBar替换下
    LBTabBar *tabbar = [[LBTabBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, USERDEFINED_TABBAR_H)];
    tabbar.myDelegate = self;
    //kvc实质是修改了系统的_tabBar
    [self setValue:tabbar forKeyPath:@"tabBar"];
    
    //登录异常相关通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginAbnormal) name:@"LoginAbnormal" object:nil];
    //修改密码相关通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(passwordAbnormal) name:@"ChangePassword" object:nil];
    //修改语言相关通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeLanguageAbnormal) name:@"ChangeLanguage" object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     
    //清空过期用户数据
//    [CacheManager clearnOuttimeMembers];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

#pragma mark - LBTabBarDelegate
//点击中间按钮的代理方法
- (void)tabBarPlusBtnClick:(LBTabBar *)tabBar
{
    self.selectedIndex = 2;
//    [[NSObject topMostOfViewController:self] presentViewController:nav animated:YES completion:nil];
//    NSLog(@"点击中间按钮");
}
#pragma mark - 初始化tabBar上除了中间按钮之外所有的按钮

- (void)setUpAllChildVc
{
    
    NSString * language = [UserManager language];
    if (language.length >0) {
        [GDLocalizableController setUserlanguage:language];
        
    }else{
        [GDLocalizableController setUserlanguage:CHINESE];
       
    }
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    HomeViewController *HomeVC = [storyBoard instantiateViewControllerWithIdentifier:@"HomeViewController"];
    NSString * name = GDLocalizedString(@"home");
    [self setUpOneChildVcWithVc:HomeVC Image:@"index_tabbar_home" selectedImage:@"index_tabbar_homea" title:name];
    name = GDLocalizedString(@"quick_order");
    PlaceOrderViewController *OrderVC = [storyBoard instantiateViewControllerWithIdentifier:@"PlaceOrderViewController"];
    [self setUpOneChildVcWithVc:OrderVC Image:@"index_tabbar_placeOrder" selectedImage:@"index_tabbar_placeOrdera" title:name];
    CustomViewController *vc = [[CustomViewController alloc] init];
    MainNavigationController *nav = [[MainNavigationController alloc] initWithRootViewController:vc];
    [self addChildViewController:nav];
    name = GDLocalizedString(@"shopping_cart");
    ShoppingCarViewController *ShopVC = [storyBoard instantiateViewControllerWithIdentifier:@"ShoppingCarViewController"];
    [self setUpOneChildVcWithVc:ShopVC Image:@"index_tabbar_shopping" selectedImage:@"index_tabbar_shoppinga" title:name];
    name = GDLocalizedString(@"my");

    ProfileViewController *profileVc = [[ProfileViewController alloc] init];
    [self setUpOneChildVcWithVc:profileVc Image:@"index_tabbar_my" selectedImage:@"index_tabbar_mya" title:name];

    
}
- (void)UploadAllChildVc
{
    
    NSString * language = [UserManager language];
    if (language.length >0) {
        [GDLocalizableController setUserlanguage:language];
        
    }else{
        [GDLocalizableController setUserlanguage:CHINESE];
        
    }
    HomeViewController *HomeVC = [self.childViewControllers objectAtIndex:0];
    
    NSString * name = GDLocalizedString(@"home");
    [self uploadTitle:HomeVC andTitle:name];
    name = GDLocalizedString(@"quick_order");
    PlaceOrderViewController *OrderVC = [self.childViewControllers objectAtIndex:1];
    [self uploadTitle:OrderVC andTitle:name];
    name = GDLocalizedString(@"shopping_cart");
    ShoppingCarViewController *ShopVC = [self.childViewControllers objectAtIndex:2];
    [self uploadTitle:ShopVC andTitle:name];
    name = GDLocalizedString(@"my");
    ProfileViewController *MineVC = [self.childViewControllers objectAtIndex:3];
    [self uploadTitle:MineVC andTitle:name];
    
}

-(void)uploadTitle:(UIViewController*)tmpVC andTitle:(NSString*)title
{
    tmpVC.tabBarItem.title = title;
    tmpVC.navigationItem.title = title;
    UILabel * label = [[UILabel alloc]init];
    label.text = title;
    [label sizeToFit];
    CGFloat imageWith = tmpVC.tabBarItem.image.size.width;
    CGFloat imageHeight = tmpVC.tabBarItem.image.size.height;
    CGFloat labelWidth = label.frame.size.width;
    CGFloat labelHeight = label.frame.size.height;
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 11) { // iOS系统版本 >= 11 .0
        tmpVC.tabBarItem.imageInsets = UIEdgeInsetsMake(-7, labelWidth/2.0, 7, -labelWidth/2.0);
        [tmpVC.tabBarItem setTitlePositionAdjustment:UIOffsetMake(-imageWith/2.0, imageHeight-7)];
    }else if (version.doubleValue >= 10.0) { // iOS系统版本 >= 11 .0
        
    }else{
        tmpVC.tabBarItem.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        [tmpVC.tabBarItem setTitlePositionAdjustment:UIOffsetMake(-70, 0)];
    }
}

#pragma mark - 初始化设置tabBar上面单个按钮的方法

/**
 *
 *  设置单个tabBarButton
 *
 *  @param Vc            每一个按钮对应的控制器
 *  @param image         每一个按钮对应的普通状态下图片
 *  @param selectedImage 每一个按钮对应的选中状态下的图片
 *  @param title         每一个按钮对应的标题
 */
- (void)setUpOneChildVcWithVc:(UIViewController *)Vc Image:(NSString *)image selectedImage:(NSString *)selectedImage title:(NSString *)title
{
//    [Vc removeFromParentViewController];
    // 选中的item普通状态图片的大小
    UIImage *normalImage = self.navigationController.tabBarController.tabBar.selectedItem.image;
    UIImage *tabNormalImage = [self createNewImageWithColor:normalImage multiple:1.0];
    tabNormalImage = [tabNormalImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.navigationController.tabBarController.tabBar.selectedItem setImage:tabNormalImage];
    // 选中的item选中撞他图片的大小
    UIImage *selectImage = self.navigationController.tabBarController.tabBar.selectedItem.selectedImage;
    UIImage *tabSelectImage = [self createNewImageWithColor:selectImage multiple:1.0];
    tabSelectImage = [tabSelectImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *myImage = [UIImage imageNamed:image];
    myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //tabBarItem，是系统提供模型，专门负责tabbar上按钮的文字以及图片展示
    Vc.tabBarItem.image = myImage;

    UIImage *mySelectedImage = [UIImage imageNamed:selectedImage];
    mySelectedImage = [mySelectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.navigationController.tabBarController.tabBar.selectedItem setSelectedImage:tabSelectImage];
    Vc.tabBarItem.selectedImage = mySelectedImage;
    
    Vc.tabBarItem.title = title;
    Vc.navigationItem.title = title;
    // 设置 tabbarItem 选中状态下的文字颜色(不被系统默认渲染,显示文字自定义颜色)
    NSDictionary *dictHome = [NSDictionary dictionaryWithObject:RGBColor(32, 32, 32) forKey:NSForegroundColorAttributeName];
    [Vc.tabBarItem setTitleTextAttributes:dictHome forState:UIControlStateSelected];
    
    CGFloat imageWith = Vc.tabBarItem.image.size.width;
    CGFloat imageHeight = Vc.tabBarItem.image.size.height;
    
    CGFloat labelWidth = 0.0;
    CGFloat labelHeight = 0.0;
    UILabel * label = [[UILabel alloc]init];
    label.text = title;
    [label sizeToFit];
    labelWidth = label.frame.size.width;
    labelHeight = label.frame.size.height;
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue >= 11) { // iOS系统版本 >= 11 .0
        Vc.tabBarItem.imageInsets = UIEdgeInsetsMake(-7, labelWidth/2.0, 7, -labelWidth/2.0);
        [Vc.tabBarItem setTitlePositionAdjustment:UIOffsetMake(-imageWith/2.0, imageHeight-7)];
    }else if (version.doubleValue >= 10.0) { // iOS系统版本 >= 11 .0
        Vc.tabBarItem.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        [Vc.tabBarItem setTitlePositionAdjustment:UIOffsetMake(0, 0)];
    }else{
        Vc.tabBarItem.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        [Vc.tabBarItem setTitlePositionAdjustment:UIOffsetMake(-70, 0)];
    }
//    if(IOS_VERSION_10){
//        Vc.tabBarItem.imageInsets = UIEdgeInsetsMake(-7, labelWidth/2.0, 7, -labelWidth/2.0);
//        [Vc.tabBarItem setTitlePositionAdjustment:UIOffsetMake(-imageWith/2.0, imageHeight-7)];
//    }else
//    {
//        Vc.tabBarItem.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
//       [Vc.tabBarItem setTitlePositionAdjustment:UIOffsetMake(-70, 0)];
//    }

    MainNavigationController *nav = [[MainNavigationController alloc] initWithRootViewController:Vc];
     [self addChildViewController:nav];

    
}

- (UIImage *) createNewImageWithColor:(UIImage *)image multiple:(CGFloat)multiple
{
    CGFloat newMultiple = multiple;
    if (multiple == 0) {
      newMultiple = 1;
    }
    else if((fabs(multiple) > 0 && fabs(multiple) < 1) || (fabs(multiple)>1 && fabs(multiple)<2))
    {
        newMultiple = multiple;
    }
    else
    {
        newMultiple = 1;
    }
    CGFloat w = image.size.width*newMultiple;
    CGFloat h = image.size.height*newMultiple;
    CGFloat scale = [UIScreen mainScreen].scale;
    UIImage *tempImage = nil;
    CGRect imageFrame = CGRectMake(0, 0, w, h);
    UIGraphicsBeginImageContextWithOptions(image.size, NO, scale);
    [[UIBezierPath bezierPathWithRoundedRect:imageFrame cornerRadius:0] addClip];
    [image drawInRect:imageFrame];
    tempImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tempImage;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - LBTabBarDelegate


-(void)setAlert:(NSString*)alertMsg
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
    
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
    }];
    
    
    /*确定按钮的颜色*/
    [okAction setValue:[UIColor redColor] forKey:@"_titleTextColor"];
    [alertController addAction:okAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

/*
 *按时间隐藏TabBar
 */
-(void)hiddenTabBarWithTime:(NSTimeInterval)time
{
    self.tabBar.hidden = YES;
    
}

-(void)hiddenTabBar{
    [self hiddenTabBarWithTime:0.37];
}

/*
 *按时间显示TabBar
 */
-(void)showTabBarWithTime:(NSTimeInterval)time
{
    self.tabBar.hidden = NO;
    
}

-(void)showTabBar{
    [self showTabBarWithTime:0.37];
}


//修改密码提示方法
-(void)passwordAbnormal
{
    UIAlertController * controller = [UIAlertController alertControllerWithTitle:@"密码修改成功" message:@"您的密码修改成功，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * defaultAction = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIStoryboard * tmpStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        MainNavigationController * MNaVC = self.selectedViewController;
        [MNaVC popToRootViewControllerAnimated:NO];
        [self changeBottomTabBarFunctionWithIndex:2];
        LoginViewController * tmpVC = [tmpStoryboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [self presentViewController:tmpVC animated:YES completion:^{
            
        }];
        
    }];
    [controller addAction:defaultAction];
    [self presentViewController:controller animated:YES completion:nil];
}
//修改语言方法
-(void)ChangeLanguageAbnormal
{
    [self UploadAllChildVc];
    
}
//登录异常提示方法
-(void)loginAbnormal
{
    UIAlertController * controller = [UIAlertController alertControllerWithTitle:@"安全提示" message:@"您的帐号异常，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * defaultAction = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIStoryboard * tmpStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        MainNavigationController * MNaVC = self.selectedViewController;
        [MNaVC popToRootViewControllerAnimated:NO];
        LoginViewController * tmpVC = [tmpStoryboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [self presentViewController:tmpVC animated:NO completion:^{
            
        }];
        
    }];
    [controller addAction:defaultAction];
    [self presentViewController:controller animated:YES completion:nil];
}


- (UIColor *)randomColor
{
    CGFloat r = arc4random_uniform(256);
    CGFloat g = arc4random_uniform(256);
    CGFloat b = arc4random_uniform(256);
    return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0];
    
}
@end
